class Shop::FareTemplatesController < ShopController
  def index
    @fare_templates = current_shoper.shop.fare_templates.order("created_at DESC").page(params[:page]).per(params[:per])
  end
  
  def show
    @fare_template = FareTemplate.find params[:id]
  end

  def new
    @fare_template = FareTemplate.new
  end

  def create
    @fare_template = FareTemplate.new fare_template_params
    @fare_template.shop_id = current_shoper.shop_id
    if @fare_template.save
      FareMode.create(fare_template_id: @fare_template.id, first_n_piece: 1, first_amount: 0.0, second_n_piece: 0, second_amount: 0.0, is_default: true)
      redirect_to shop_fare_templates_path, notice: "保存成功！"
    else
      redirect_to shop_fare_templates_path, notice: "保存失败！"
    end
  end

  def edit
    @fare_template = FareTemplate.find params[:id]
  end

  def update
    @fare_template = FareTemplate.find params[:id]
    if @fare_template.update fare_template_params
      redirect_to shop_fare_templates_path, notice: "更新成功！"
    else
      redirect_to shop_fare_templates_path, notice: "更新失败！"
    end
  end
  
  def destroy
    @fare_template = FareTemplate.find params[:id]
    if @fare_template.spus.count > 0
      redirect_to shop_fare_templates_path, notice: "删除失败，有商品关联该模版." and return
    end
    if @fare_template.destroy
      redirect_to shop_fare_templates_path, notice: "删除成功."
    else
      redirect_to shop_fare_templates_path, notice: "删除失败."
    end
  end

  private

  def fare_template_params
    params.require(:fare_template).permit(:name, :fare_method, :compute_method)
  end
end
